import { useEffect, useMemo, useState } from "react";
import { getComponentById, useComponentStore } from "../../editor/stores/components";

interface HoverMaskProps {
    containerClassName: string;
    componentId: string;
}

export function HoverMask({ containerClassName, componentId }: HoverMaskProps){
    const { components } = useComponentStore()

    const [position, setPostion] = useState({
        left: 0,
        top: 0,
        width: 0,
        height: 0,
    })

    useEffect(() => {
        updatePosition()
    }, [componentId])

    const curComponent = useMemo(() => {
        return getComponentById(componentId, components)
    }, [componentId])


    function updatePosition(){
        if (!componentId) return;

        const containerElement = document.querySelector(`.${containerClassName}`)
        if(!containerElement) return

        const componentElement = containerElement.querySelector(`[data-component-id='${componentId}']`)
        if (!componentElement) return

        const { left, top, width, height } = componentElement.getBoundingClientRect()
        const { left: containerLeft, top: containerTop } = containerElement.getBoundingClientRect()

        setPostion({
            left: left - containerLeft + containerElement.scrollLeft,
            top: top - containerTop + containerElement.scrollTop,
            width: width,
            height: height,
        })
    }

    return (
        <div className="hover-mask" style={{
            position: 'absolute',
            zIndex: 11,
            left: position.left,
            top: position.top,
            width: position.width,
            height: position.height,
            backgroundColor: 'rgba(0, 0, 255, 0.1)',
            pointerEvents: 'none',
        }}>
            <div className="hover-mask__content" style={{
                position: 'absolute',
                zIndex: 12,
                right: 0,
                top: position.top <= 0 ? 0 : -22,
                backgroundColor: 'rgba(0, 0, 255, 1)',
                color: '#fff',
                padding: '2px 10px',
                borderRadius: '3px',
                fontSize: '12px',
            }}>
                {curComponent?.desc}
            </div>
        </div>
    )
}